package com.android.studyspot;



import java.net.MalformedURLException;
import java.util.List;

import com.actionbarsherlock.app.SherlockActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.common.SignInButton;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableOperationCallback;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;

import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;


public class LoginActivity extends SherlockActivity implements ConnectionCallbacks, OnConnectionFailedListener {	
	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
    private ProgressDialog mConnectionProgressDialog;
    private PlusClient mPlusClient;
    private ConnectionResult mConnectionResult;
    private SignInButton mSignInButton;
    private MobileServiceClient mClient;
    private String accountName;
    private String firstName;
    private String lastName;
    private users user;
    private MobileServiceTable<users> mUsersTable;
        
    private static final  int CAL_POLY_ID = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_login);
		
		// Connect to Study Spot Azure Mobile Service
		try {
			mClient = new MobileServiceClient(
					 "https://studyspot.azure-mobile.net/",
					 "UeeXTmfsscRIhhVuCyRqDRwfThBDPa90",
					 this
			);
			
			mUsersTable = mClient.getTable(users.class);
			
		}
		catch (MalformedURLException e) {
			Log.d("Azure", e.getMessage());
			e.printStackTrace();
		}
		
		mPlusClient = new PlusClient.Builder(this, this, this)
        .setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
        .build();
		// Progress bar to be displayed if the connection failure is not resolved.
		mConnectionProgressDialog = new ProgressDialog(this);
		mConnectionProgressDialog.setMessage("Signing in...");
		
		this.mSignInButton = (SignInButton)this.findViewById(R.id.sign_in_button);
		initListeners();
	}
	
	@Override
    protected void onStart() {
        super.onStart();
        Log.d("study-spot", "onStart()");
        
        //mPlusClient.connect();      
    }
	
	@Override
    protected void onStop() {
        super.onStop();
        mPlusClient.disconnect();
    }
	
	@Override
    public void onConnectionFailed(ConnectionResult result) {
      if (mConnectionProgressDialog.isShowing()) {
        // The user clicked the sign-in button already. Start to resolve
        // connection errors. Wait until onConnected() to dismiss the
        // connection dialog.
        if (result.hasResolution()) {
          try {
                   result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
           } catch (SendIntentException e) {

               Log.d("study-spot", "onConnectionFailed()");
                   mPlusClient.connect();
           }
        }
      }
      // Save the result and resolve the connection failure upon a user click.
      mConnectionResult = result;
    }
	
	@Override
    protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
		if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
            mConnectionResult = null;
            Log.d("study-spot", "onActivityResult()");
            			
            mPlusClient.connect();
        }
    }
	
	@Override
    public void onConnected(Bundle connectionHint) {
        accountName = mPlusClient.getAccountName();
        firstName = mPlusClient.getCurrentPerson().getName().getGivenName();
        lastName = mPlusClient.getCurrentPerson().getName().getFamilyName();
        
        insertNewUser();
    }

    @Override
    public void onDisconnected() {
        Log.d("StudySpot", "disconnected");
    }
	
	private void initListeners() {
		this.mSignInButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (v.getId() == R.id.sign_in_button){
					if(!mPlusClient.isConnected()) {
					
						mPlusClient.connect();
						
			            if (mConnectionResult == null) {
			                mConnectionProgressDialog.show();
			            } else {
			                try {
			                    mConnectionResult.startResolutionForResult(LoginActivity.this, REQUEST_CODE_RESOLVE_ERR);
			                } catch (SendIntentException e) {
			                    // Try connecting again.
			                    mConnectionResult = null;
			                    mPlusClient.connect();
			                    Log.d("study-spot", "initListeners()");
			                }
			            }
			        }
					
					Log.d("study-spot", "sign in button pressed");
				}
				
			}
			
		});
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            return true;
        }
        return false;
    }
	
	private void insertNewUser() {
		user = new users();
		user.firstname = firstName;
		user.lastname = lastName;
		user.email = accountName;
		user.u_school_id = LoginActivity.CAL_POLY_ID;
		
		this.mUsersTable.where().field("email").eq(accountName)
		.execute(new TableQueryCallback<users>() {

			@Override
			public void onCompleted(List<users> result, int count, Exception exception,
					ServiceFilterResponse response) {
								
				if (exception == null) {
					if (result.size() == 0) {
						mUsersTable.insert(user, new TableOperationCallback<users>() {

							@Override
							public void onCompleted(users entity, Exception exception,
									ServiceFilterResponse response) {
								if (exception == null) {
									Intent userProfileStart = new Intent(LoginActivity.this, UserProfileActivity.class);
									userProfileStart.putExtra("userId", entity.id);
									startActivity(userProfileStart);
								}
								else {
									Log.e("Add Courses", exception.getMessage());
								}
							}
						});
					}
					else {
						Intent userProfileStart = new Intent(LoginActivity.this, UserProfileActivity.class);
						userProfileStart.putExtra("userId", result.get(0).id);
						startActivity(userProfileStart);
					}
				}
				else {
					Log.e("StudySpot", exception.getMessage());
				}
				
			}
			
		});
	
		
	}
}

